{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 统计函数",
   "id": "e9e7a50bae6d186c"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 1.求所有元素的积\n",
    "使用函数torch.prod()求所有函数的积,语法如下：\n",
    "```python\n",
    "torch.prod(input,dim=None,keepdim=False)\n",
    "```\n",
    "torch.prod()是一个PyTorch函数，用于计算张量（Tensor）中所有元素的乘积。它接受一个张量作为输入，并返回一个标量值，表示输入张量中所有元素的乘积。\n",
    "#### 【代码说明】\n",
    "+ input: 输入张量.\n",
    "+ dim: 指定沿哪个纬度进行乘积运算，默认值为None,表示计算整个张量的乘积。如果指定了纬度，那么结果将是一个降低该纬度的张量.\n",
    "+ keepdim: 布尔值，表示是否保存原始张量的纬度，默认值为False,表示不保持原始纬度.如果设置为True,则结果张量的维度与输入张量相同，但指定的维度为1.\n",
    "示例代码如下："
   ],
   "id": "cacca29576d7af2f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-07T09:50:11.000891Z",
     "start_time": "2025-03-07T09:50:07.679601Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "\n",
    "# 创建一个2x2的张量a\n",
    "a = torch.tensor([[1, 2,],[3, 4]])\n",
    "\n",
    "# 计算张量a中所有元素的乘积，并将结果赋值给result_dim\n",
    "result = torch.prod(a)\n",
    "print(result)\n",
    "\n",
    "# 沿着第0维（行）计算张量a中元素的乘积，并将结果赋值给result_dim\n",
    "result_dim = torch.prod(a,dim=0)\n",
    "print(result_dim)\n",
    "\n",
    "#沿着第0维（行）计算张量a中元素的乘积，并保持原始维度，将结果赋值给result_keepdim\n",
    "result_keepdim = torch.prod(a,dim=1,keepdim=True)\n",
    "print(result_keepdim)"
   ],
   "id": "7958ff5bd7c06f6c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(24)\n",
      "tensor([3, 8])\n",
      "tensor([[ 2],\n",
      "        [12]])\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 2.求和\n",
    "使用torch.sum()函数求和，该函数对输入的张量数据的某一维度求和，一共有两种格式。\n",
    "#### 第一种格式:\n",
    "```python\n",
    "torch.sum(input,dtype=None)\n",
    "```\n",
    "计算输入张量input中所有元素的和，返回一个标量值。\n",
    "#### 第二种格式：\n",
    "```python\n",
    "torch.sum(input,dim,keepdim=False,dtype=None)\n",
    "```\n",
    "计算输入张量input在指定维度dim上的和，并返回一个新的张量。\n",
    "#### 【代码说明】\n",
    "+ input: 输入一个张量.\n",
    "+ dim: 要求和的维度，可以是一个列表。当dim=0时，即第0个维度会缩减，也就是说将N行压缩成一行，故相当于对列进行求和；当dim=1时，对行进行求和。\n",
    "+ keepdim: 求和之后这个dim的元素个数为1,所以要被去掉，如果要保留这个维度，则要保证keepdim=True.如果keepdim为True,则保留原始张量的维度；如果keepdim为False,则不保留原始张量的维度。\n",
    "首先,创建初始\n"
   ],
   "id": "83bf8afe72f06c8"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
